<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python,django,mysql,">










<meta name="description" content="介绍Django是一个开放源代码的Web应用框架，由Python写成。">
<meta name="keywords" content="python,django,mysql">
<meta property="og:type" content="article">
<meta property="og:title" content="学习Django框架">
<meta property="og:url" content="http://Anzusen.com/2019/04/11/学习Django框架/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="介绍Django是一个开放源代码的Web应用框架，由Python写成。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/success_django.png">
<meta property="og:updated_time" content="2020-04-06T13:06:04.552Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="学习Django框架">
<meta name="twitter:description" content="介绍Django是一个开放源代码的Web应用框架，由Python写成。">
<meta name="twitter:image" content="http://anzusen.com/image/success_django.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/04/11/学习Django框架/">





  <title>学习Django框架 | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/04/11/学习Django框架/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">学习Django框架</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-11T18:12:21+08:00">
                2019-04-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/框架/" itemprop="url" rel="index">
                    <span itemprop="name">框架</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/04/11/学习Django框架/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/04/11/学习Django框架/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h4><p>Django是一个开放源代码的Web应用框架，由Python写成。<br><a id="more"></a></p>
<h4 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h4><ul>
<li>pycharm社区版创建django项目：<a href="https://www.cnblogs.com/fanyuchen/p/6918735.html" target="_blank" rel="noopener">pycharm自带django数据包</a></li>
</ul>
<h4 id="项目"><a href="#项目" class="headerlink" title="项目"></a>项目</h4><h5 id="pycharm创建"><a href="#pycharm创建" class="headerlink" title="pycharm创建"></a>pycharm创建</h5><h6 id="第一个django请求"><a href="#第一个django请求" class="headerlink" title="第一个django请求"></a>第一个django请求</h6><h6 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h6><ol>
<li>在你要创建项目的目录下执行cmd命令<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">django-admin.py startproject 文件名</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行之后可以看到项目的目录结构<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">hellodjango</span><br><span class="line">|-- hellodjango</span><br><span class="line">|   |-- __init__.py</span><br><span class="line">|   |-- settings.py</span><br><span class="line">|   |-- urls.py</span><br><span class="line">|   `-- wsgi.py</span><br><span class="line">`-- manage.py</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li><p>运行:我们进入 hellodjango 目录(pycharm下，点击 Terminal)，输入以下命令，启动服务器：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python3 manage.py runserver 127.0.0.1:8000</span><br></pre></td></tr></table></figure>
</li>
<li><p>打开显示的网址()，可以看到第一个django请求运行成功.</p>
</li>
</ol>
<p><img src="/image/success_django.png" alt="第一个django请求"></p>
<p>#######  目录说明：</p>
<ul>
<li>HelloWorld: 项目的容器。</li>
<li>manage.py: 一个实用的命令行工具，可让你以各种方式与该 Django 项目进行交互。</li>
<li>HelloWorld/<strong>init</strong>.py: 一个空文件，告诉 Python 该目录是一个 Python 包。</li>
<li>HelloWorld/settings.py: 该 Django 项目的设置/配置。</li>
<li>HelloWorld/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站”目录”。</li>
<li>HelloWorld/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口，以便运行你的项目。<h5 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h5>在settings.py文件中修改：</li>
</ul>
<ol>
<li>模板路径配置（html）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">TEMPLATES = [</span><br><span class="line">    &#123;</span><br><span class="line">        ...</span><br><span class="line">        <span class="string">'DIRS'</span>: [os.path.join(BASE_DIR,<span class="string">'templates'</span>)],</span><br><span class="line">        <span class="comment"># os.path.join(BASE_DIR）表示基目录，你的project目录</span></span><br><span class="line">        <span class="comment"># 'templates'表示模板路径</span></span><br><span class="line">        ...</span><br><span class="line">    &#125;,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>静态文件配置（图片，css文件, js文件）</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">STATIC_URL = &apos;/static/&apos; # 使用时前缀</span><br><span class="line">STATICFILES_DIRS=(</span><br><span class="line">    os.path.join(BASE_DIR,&apos;static&apos;), # 真实路径，干脆直接写成&apos;static&apos;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><strong>注意：逗号不能少！！！</strong></p>
<ol start="3">
<li>额外配置（csrf注释）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">MIDDLEWARE = [</span><br><span class="line">    <span class="string">'django.middleware.security.SecurityMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.contrib.sessions.middleware.SessionMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.common.CommonMiddleware'</span>,</span><br><span class="line">    <span class="comment"># 'django.middleware.csrf.CsrfViewMiddleware',</span></span><br><span class="line">    <span class="string">'django.contrib.auth.middleware.AuthenticationMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.contrib.messages.middleware.MessageMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.clickjacking.XFrameOptionsMiddleware'</span>,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h5 id="路由关系-url对应关系"><a href="#路由关系-url对应关系" class="headerlink" title="路由关系(url对应关系)"></a>路由关系(url对应关系)</h5><p>url—&gt;函数</p>
<ul>
<li>注释自带的url(path)，按照自带格式创建你的页面<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># path(&apos;admin/&apos;, admin.site.urls),</span><br><span class="line">   url(r&apos;^login/&apos;,login),</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="处理请求函数"><a href="#处理请求函数" class="headerlink" title="处理请求函数"></a>处理请求函数</h5><p>先看整体代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> HttpResponse,render,redirect</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment"># return HttpResponse('hahahhahahah')</span></span><br><span class="line">    <span class="comment"># 自动找到模板路径下的html文件，读取类容并返回给用户</span></span><br><span class="line">    print(request.GET)</span><br><span class="line">    <span class="keyword">if</span> request.method==<span class="string">"GET"</span>:</span><br><span class="line">        <span class="comment"># 模板渲染</span></span><br><span class="line">        <span class="keyword">return</span> render(request,<span class="string">'login.html'</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="comment"># 用户post提交的数据（请求体）</span></span><br><span class="line">        u = request.POST.get(<span class="string">'username'</span>)</span><br><span class="line">        p = request.POST.get(<span class="string">'password'</span>)</span><br><span class="line">        <span class="keyword">if</span> u==<span class="string">'root'</span><span class="keyword">and</span> p==<span class="string">'123123'</span>:</span><br><span class="line">            <span class="comment"># 登陆成功,跳转到其他页面</span></span><br><span class="line">            <span class="keyword">return</span> redirect(<span class="string">'https://www.youdao.com/'</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 登陆失败</span></span><br><span class="line">            <span class="keyword">return</span> render(request,<span class="string">'login.html'</span>,&#123;<span class="string">'msg'</span>:<span class="string">'用户名或密码错误'</span>&#125;)</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    <span class="comment"># path('admin/', admin.site.urls),</span></span><br><span class="line">    url(<span class="string">r'^login/'</span>,login),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>步骤说明：</p>
<ol>
<li><p>导入包</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">from django.shortcuts import HttpResponse,render,redirect</span><br></pre></td></tr></table></figure>
</li>
<li><p>定义函数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">def indox(request):</span><br><span class="line"></span><br><span class="line">    函数体</span><br></pre></td></tr></table></figure>
</li>
<li><p>request的两种方法（request.method）:</p>
</li>
</ol>
<ul>
<li>request.GET   , 从请求头中的url拿到值， GET请求只有request.GET有值</li>
<li>request.POST ,从请求头中拿到值， POST请求request.GET和request.POST都可能有值</li>
<li>request表示用户请求相关的所有信息（对象）</li>
</ul>
<ol start="4">
<li>三种返回方式：</li>
</ol>
<ul>
<li>return HttpResponse（”字符串”），只能在页面上显示支付串</li>
<li>return render(函数参数（request）,’模板路径’（login.html），{})， 自带找到模板路径下的login.html，读取内容并返回给用户，模板路径是templates以后的路径。</li>
<li>return redirect(‘URL’)，跳转到要跳转的网址（可以是其他网站，也可以是自己的网址）</li>
</ul>
<ol start="5">
<li>说明：在前面我们已经配置过模板路径和静态文件路径,所以可以直接运用自己web网页设计知识对你的页面进行设计、美化和动态交互，记得在你html文件中要连接css、js或图片文件时，前面添加路径（/static/），例如：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;link rel=&quot;stylesheet&quot; href=&quot;/static/commons.css&quot;/&gt;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="模板标签"><a href="#模板标签" class="headerlink" title="模板标签"></a>模板标签</h5><h6 id="过滤器"><a href="#过滤器" class="headerlink" title="过滤器"></a>过滤器</h6><p>urls.py<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line"><span class="keyword">return</span> render(request,<span class="string">'模板路径‘)，</span></span><br><span class="line"><span class="string">&#123;</span></span><br><span class="line"><span class="string">    '</span>k1<span class="string">':'</span>v1<span class="string">',</span></span><br><span class="line"><span class="string">    '</span>k2<span class="string">':[1,2,32,34],#列表</span></span><br><span class="line"><span class="string">    '</span>k3<span class="string">':&#123;'</span>k1<span class="string">':'</span>v1<span class="string">','</span>k2<span class="string">':'</span>v2<span class="string">',...&#125;,# 字典</span></span><br><span class="line"><span class="string">    '</span>user_list_dict<span class="string">':[&#123;&#125;] ，#列表[字典]</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure></p>
<p>index.html<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;h1&gt;&#123;&#123;k1&#125;&#125;&lt;/h1&gt;</span><br><span class="line">&lt;h1&gt;&#123;&#123;k2.2&#125;&#125;&lt;/h1&gt;</span><br><span class="line">&lt;h1&gt;&#123;&#123;k3.&#125;&#125;&lt;/h1&gt;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>模板过滤器可以在变量被显示前修改它，过滤器使用管道字符，如下所示：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; name|lower &#125;&#125;</span><br></pre></td></tr></table></figure>
<p>name  变量被过滤器 lower 处理后，文档大写转换文本为小写。</p>
<ul>
<li>过滤管道可以被<em> 套接</em> ，既是说，一个过滤器管道的输出又可以作为下一个管道的输入：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; my_list|first|upper &#125;&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>以上实例将第一个元素并将其转化为大写。</p>
<ul>
<li>有些过滤器有参数。 过滤器的参数跟随冒号之后并且总是以双引号包含。 例如：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; bio|truncatewords:&quot;30&quot; &#125;&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>这个将显示变量 bio 的前30个词。</p>
<ul>
<li>其他过滤器：</li>
</ul>
<ol>
<li>addslashes : 添加反斜杠到任何反斜杠、单引号或者双引号前面。</li>
<li>date : 按指定的格式字符串参数格式化 date 或者 datetime 对象，实例：</li>
<li><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; pub_date|date:&quot;F j, Y&quot; &#125;&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>length : 返回变量的长度。</p>
</li>
</ol>
<p><strong>说明</strong>：django标签通过 ‘.’ 索引</p>
<h6 id="if-else-标签"><a href="#if-else-标签" class="headerlink" title="if/else 标签"></a>if/else 标签</h6><p>基本语法格式如下：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;% if condition %&#125;</span><br><span class="line">     ... display</span><br><span class="line">&#123;% endif %&#125;</span><br></pre></td></tr></table></figure>
<p>或者：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;% if condition1 %&#125;</span><br><span class="line">   ... display 1</span><br><span class="line">&#123;% elif condition2 %&#125;</span><br><span class="line">   ... display 2</span><br><span class="line">&#123;% else %&#125;</span><br><span class="line">   ... display 3</span><br><span class="line">&#123;% endif %&#125;</span><br></pre></td></tr></table></figure></p>
<p>根据条件判断是否输出。if/else 支持嵌套。</p>
<ul>
<li><strong>说明：</strong> if 标签接受 and ， or 或者 not 关键字来对多个变量做判断 ，或者对变量取反（ not )。</li>
</ul>
<h6 id="循环"><a href="#循环" class="headerlink" title="循环"></a>循环</h6><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h3</span>&gt;</span>循环<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">&#123;% for item in users%&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123;item&#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">&#123;% endfor %&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>说明</strong>： 可以与html搭配使用</li>
</ul>
<h6 id="ifequal-ifnotequal-标签"><a href="#ifequal-ifnotequal-标签" class="headerlink" title="ifequal/ifnotequal 标签"></a>ifequal/ifnotequal 标签</h6><p> ifequal  标签比较两个值，当他们相等时，显示在 ifequal 和  endifequal 之中所有的值。</p>
<p>下面的例子比较两个模板变量 user 和 currentuser :</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;% ifequal user currentuser %&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Welcome!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">&#123;% endifequal %&#125;</span><br></pre></td></tr></table></figure>
<p>和 if  类似，  ifequal 支持可选的 else标签：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;% ifequal section 'sitenews' %&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Site News<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">&#123;% else %&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>No News Here<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">&#123;% endifequal %&#125;</span><br></pre></td></tr></table></figure>
<h6 id="注释标签"><a href="#注释标签" class="headerlink" title="注释标签"></a>注释标签</h6><p>Django 注释使用 。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;# 这是一个注释 #&#125;</span><br></pre></td></tr></table></figure>
<h6 id="include-标签"><a href="#include-标签" class="headerlink" title="include 标签"></a>include 标签</h6><p> include 标签允许在模板中包含其它的模板的内容。</p>
<p>下面这个例子都包含了 nav.html 模板：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;% include &quot;nav.html&quot; %&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="模板继承"><a href="#模板继承" class="headerlink" title="模板继承"></a>模板继承</h5><p>模板可以用继承的方式来实现复用。</p>
<p>接下来我们先创建之前项目的 templates 目录中添加 father.html 文件，代码如下：</p>
<ul>
<li>mysites/templates/father.html 文件代码：<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">title</span>&gt;</span>模板继承<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Hello World!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>Django 测试。<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    &#123;% block mainbody %&#125;</span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>original<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    &#123;% endblock %&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>以上代码中，名为 mainbody 的 block 标签是可以被继承者们替换掉的部分。</p>
<p>所有的  block 标签告诉模板引擎，子模板可以<strong>重载</strong>这些部分。</p>
<p>son.html 中继承 father.html，并替换特定 block，son.html 修改后的代码如下：</p>
<ul>
<li>mysites/templates/son.html 文件代码：</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;%extends "father.html" %&#125;</span><br><span class="line"> </span><br><span class="line">&#123;% block mainbody %&#125;</span><br><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>继承了 base.html 文件<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">&#123;% endblock %&#125;</span><br></pre></td></tr></table></figure>
<p>第一行代码说明 son.html 继承了 father.html 文件。可以看到，这里相同名字的 block 标签用以替换 father.html 的相应 block。</p>
<h5 id="django模型"><a href="#django模型" class="headerlink" title="django模型"></a>django模型</h5><p>Django 对各种数据库提供了很好的支持，包括：PostgreSQL、MySQL、SQLite、Oracle。</p>
<p>Django 为这些数据库提供了统一的调用API。</p>
<h6 id="安装mysqlclient"><a href="#安装mysqlclient" class="headerlink" title="安装mysqlclient"></a>安装mysqlclient</h6><p>直接在pycharm的setting里面导入mysqlclient包,如果提示安装错误可以查看下面的链接：<br><a href="https://blog.51cto.com/jiaszwx/2327440" target="_blank" rel="noopener">mysqlclient安装出错 </a></p>
<h6 id="数据库配置"><a href="#数据库配置" class="headerlink" title="数据库配置"></a>数据库配置</h6><p>我们在项目的 settings.py 文件中找到 DATABASES 配置项，将其信息修改为：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">DATABASES = &#123;</span><br><span class="line">    <span class="string">'default'</span>: &#123;</span><br><span class="line">        <span class="string">'ENGINE'</span>: <span class="string">'django.db.backends.mysql'</span>,  <span class="comment"># 或者使用 mysql.connector.django</span></span><br><span class="line">        <span class="string">'NAME'</span>: <span class="string">'test_db'</span>,<span class="comment"># 数据库名称</span></span><br><span class="line">        <span class="string">'USER'</span>: <span class="string">'root'</span>,<span class="comment"># 用户</span></span><br><span class="line">        <span class="string">'PASSWORD'</span>: <span class="string">'an1234'</span>,<span class="comment"># 密码</span></span><br><span class="line">        <span class="string">'HOST'</span>:<span class="string">'localhost'</span>,<span class="comment"># ip</span></span><br><span class="line">        <span class="string">'PORT'</span>:<span class="string">'3306'</span>,<span class="comment"># 端口</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>注意：</strong>这里添加了中文注释，所以你需要在 HelloWorld/settings.py 文件头部添加 # -<em>- coding: UTF-8 -</em>-。</p>
<p>上面包含数据库名称和用户的信息，它们与 MySQL 中对应数据库和用户的设置相同。Django 根据这一设置，与 MySQL 中相应的数据库和用户连接起来。</p>
<h6 id="定义模型"><a href="#定义模型" class="headerlink" title="定义模型"></a>定义模型</h6><ol>
<li>创建 APP<br>Django规定，如果要使用模型，必须要创建一个app。我们使用以下命令创建一个 TestModel 的 app:</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">django-admin startapp TestModel</span><br></pre></td></tr></table></figure>
<p>目录结构如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Hellodjango</span><br><span class="line">|-- TestModel</span><br><span class="line">|   |-- __init__.py</span><br><span class="line">|   |-- admin.py</span><br><span class="line">|   |-- models.py</span><br><span class="line">|   |-- tests.py</span><br><span class="line">|   `-- views.py</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li>修改 TestModel/models.py 文件：</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">from django.db import models</span><br><span class="line"></span><br><span class="line">class Test(models.Model):</span><br><span class="line">    name = models.CharField(max_length=20)</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>接下来在settings.py中找到INSTALLED_APPS这一项，如下：</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = (</span><br><span class="line">    &apos;django.contrib.admin&apos;,</span><br><span class="line">    &apos;django.contrib.auth&apos;,</span><br><span class="line">    &apos;django.contrib.contenttypes&apos;,</span><br><span class="line">    &apos;django.contrib.sessions&apos;,</span><br><span class="line">    &apos;django.contrib.messages&apos;,</span><br><span class="line">    &apos;django.contrib.staticfiles&apos;,</span><br><span class="line">    &apos;TestModel&apos;,               # 添加此项</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>在命令行中运行：</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">$ python manage.py migrate   # 创建表结构</span><br><span class="line"></span><br><span class="line">$ python manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更</span><br><span class="line">$ python manage.py migrate TestModel   # 创建表结构</span><br></pre></td></tr></table></figure>
<p>看到几行 “Creating table…” 的字样，你的数据表就创建好了。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Creating tables ...</span><br><span class="line">……</span><br><span class="line">Creating table TestModel_test  #我们自定义的表</span><br><span class="line">……</span><br></pre></td></tr></table></figure></p>
<p>表名组成结构为：应用名_类名（如：TestModel_test）。</p>
<p><strong>注意</strong>：尽管我们没有在models给表设置主键，但是Django会自动添加一个id作为主键。</p>
<p>接下来你就可以对数据库进行操作了</p>
<h6 id="相关链接"><a href="#相关链接" class="headerlink" title="相关链接"></a>相关链接</h6><ul>
<li><a href="https://yq.aliyun.com/articles/609491" target="_blank" rel="noopener">python3 django配置数据库（mysql）</a></li>
<li><a href="https://blog.csdn.net/g7511991/article/details/80983276" target="_blank" rel="noopener">Django中数据库配置</a></li>
<li><a href="https://www.cnblogs.com/wcwnina/p/8719482.html" target="_blank" rel="noopener">Django 配置MySQL数据库</a></li>
<li><a href="https://blog.csdn.net/FightFightFight/article/details/80013032" target="_blank" rel="noopener"> Django(五) 配置mysql数据库</a></li>
<li><a href="https://www.cnblogs.com/rinka/p/django_database_setting.html" target="_blank" rel="noopener">django-数据库【配置】</a></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
            <a href="/tags/django/" rel="tag"># django</a>
          
            <a href="/tags/mysql/" rel="tag"># mysql</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/30/python巩固/" rel="next" title="python巩固">
                <i class="fa fa-chevron-left"></i> python巩固
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/17/Python-MySQL数据库/" rel="prev" title="Python_MySQL数据库">
                Python_MySQL数据库 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#介绍"><span class="nav-number">1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#安装"><span class="nav-number">2.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#项目"><span class="nav-number">3.</span> <span class="nav-text">项目</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#pycharm创建"><span class="nav-number">3.1.</span> <span class="nav-text">pycharm创建</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#第一个django请求"><span class="nav-number">3.1.1.</span> <span class="nav-text">第一个django请求</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#步骤"><span class="nav-number">3.1.2.</span> <span class="nav-text">步骤</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#配置"><span class="nav-number">3.2.</span> <span class="nav-text">配置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#路由关系-url对应关系"><span class="nav-number">3.3.</span> <span class="nav-text">路由关系(url对应关系)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#处理请求函数"><span class="nav-number">3.4.</span> <span class="nav-text">处理请求函数</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#模板标签"><span class="nav-number">3.5.</span> <span class="nav-text">模板标签</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#过滤器"><span class="nav-number">3.5.1.</span> <span class="nav-text">过滤器</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#if-else-标签"><span class="nav-number">3.5.2.</span> <span class="nav-text">if/else 标签</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#循环"><span class="nav-number">3.5.3.</span> <span class="nav-text">循环</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#ifequal-ifnotequal-标签"><span class="nav-number">3.5.4.</span> <span class="nav-text">ifequal/ifnotequal 标签</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#注释标签"><span class="nav-number">3.5.5.</span> <span class="nav-text">注释标签</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#include-标签"><span class="nav-number">3.5.6.</span> <span class="nav-text">include 标签</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#模板继承"><span class="nav-number">3.6.</span> <span class="nav-text">模板继承</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#django模型"><span class="nav-number">3.7.</span> <span class="nav-text">django模型</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#安装mysqlclient"><span class="nav-number">3.7.1.</span> <span class="nav-text">安装mysqlclient</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#数据库配置"><span class="nav-number">3.7.2.</span> <span class="nav-text">数据库配置</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#定义模型"><span class="nav-number">3.7.3.</span> <span class="nav-text">定义模型</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#相关链接"><span class="nav-number">3.7.4.</span> <span class="nav-text">相关链接</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
